package org.example.currency;

import static java.util.concurrent.ThreadLocalRandom.current;

import cn.hutool.core.util.RandomUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
 * @Title : TimerTest
 * @Description:
 * @author: libo@juzishuke.com
 * @date: 2023/12/6 16:03
 * @Version:1.0
 */
@Slf4j
public class TimerTest {

    private volatile static ConcurrentHashMap<String, List<String>> delayDatas = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        TimerTest test = new TimerTest();
        test.test();
    }

    public void test() {
        Timer timer = new Timer();
        Executor executor = Executors.newCachedThreadPool();
        System.out.println("开始");
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            String key = finalI % 2 + "";
            delayDatas.put(key, new ArrayList<>());
            executor.execute(() -> {
                while (true) {
//                    synchronized (delayDatas) {
                        List<String> res = delayDatas.get(key);
                        res.add(RandomUtil.randomString(3));
                        System.out.println(
                                Thread.currentThread().getName() + "生产 key : " + key + " i : "
                                        + finalI + " data " + res);
                        //                        delayDatas.putIfAbsent(key, res);
//                    }
                    try {
                        TimeUnit.SECONDS.sleep(current().nextInt(5));
                        //                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    List<String> datas = delayDatas.remove(key);
                    if (datas != null && !datas.isEmpty()) {
                        System.out.println(
                                Thread.currentThread().getName() + "消费:" + key + "   " + datas);
                    }
                }
            }, 1000, 5000);
        }

    }
}
